import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;

public class Demo2 {
    public static void main(String[] args) throws Exception {
        //工厂实例
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        //解析器
        DocumentBuilder db = dbf.newDocumentBuilder();

        //解析文件
        Document doc = db.parse("src/收藏信息.xml");

        Element brand = doc.createElement("Brand");
        brand.setAttribute("name","Vivo");

        Element type = doc.createElement("Type");
        type.setAttribute("name","SE");

        brand.appendChild(type);
        Node phoneInfo = doc.getElementsByTagName("PhoneInfo").item(0);
        phoneInfo.appendChild(brand);

        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource domSource = new DOMSource(doc);
        transformer.setOutputProperty(OutputKeys.ENCODING,"utf-8");
        StreamResult streamresult = new StreamResult(new FileOutputStream("src/收藏信息.xml"));
        transformer.transform(domSource,streamresult);
    }
}
